<template>
  <div class="searchContainer">
    <!-- 搜索框 -->
    <div class="search">
      <form action="/">
        <van-search
          v-model="value"
          :show-action="searchFlag !== 3"
          placeholder="请输入商品名称"
          @search="onSearch(value, 'userhand')"
          @cancel="onCancel"
          @focus="onFocus"
          @input="onInput"
        />
      </form>
    </div>

    <!-- 热搜 -->
    <div class="record-hot" v-show="searchFlag === 1">
      <!-- 历史记录 -->
      <div class="record-wrap" v-show="searchRecordHistory.length">
        <div class="record">
          <div class="recordText">历史记录</div>
          <van-icon @click="deleteHistory" class="delete" name="delete-o" />
        </div>
        <div class="tag-list">
          <van-tag
            @click="onSearch(searchRecord, 'history')"
            class="tag"
            plain
            size="large"
            v-for="(searchRecord, index) in searchRecordHistory"
            :key="index"
            >{{
              searchRecord.length >= 10
                ? searchRecord.slice(0, 10) + '...'
                : searchRecord
            }}</van-tag
          >
        </div>
      </div>

      <!-- 中间灰色间隔条 -->
      <div class="gray" v-show="searchRecordHistory.length"></div>

      <!-- 实时热门搜索 -->
      <div class="hot-search">
        <div class="hot-search-text">热门搜索</div>
        <div class="tag-list">
          <van-tag
            class="tag"
            :color="defaultIndex === index ? '#dd1a21' : ''"
            :class="{ active: defaultIndex === index }"
            @click="toSearchShopList(hotKeyWord.keyword, false, 'hot')"
            plain
            size="large"
            v-for="(hotKeyWord, index) in hotKeywordList"
            :key="index"
            >{{ hotKeyWord.keyword }}</van-tag
          >
        </div>
      </div>
    </div>

    <!-- 搜索中展示列表 -->
    <div class="search-inp" v-show="searchFlag === 2">
      <div
        @click="onSearch(keyword, 'autoComplete')"
        class="search-tag"
        v-for="(keyword, index) in keywordList"
        :key="index"
      >
        <van-cell class="cell" :title="keyword" is-link />
      </div>
    </div>

    <!-- 搜索得到的商品列表 -->
    <SearchShopList
      @priceAndCategorySort="priceAndCategorySort"
      v-show="searchFlag === 3"
      :handlerIndex.sync="currentCategoryIndex"
      :sonSpaceFlag="sonSpaceFlag"
      ref="searchShopList"
    ></SearchShopList>

    <!-- 搜索结果为空的空白页面 -->
    <DefaultPage
      v-show="searchFlag === 4"
      :text="'您寻找的商品还未上架'"
    ></DefaultPage>
  </div>
</template>

<script>
import debounce from 'lodash/debounce';
import { mapGetters, mapState } from 'vuex';
import SearchShopList from './components/SearchShopList';
import { Toast } from 'vant';
export default {
  name: 'Search',
  data() {
    return {
      value: '', // 搜索框的内容
      defaultIndex: 0, // 热门搜索的默认index
      keywordList: [], // 关键词列表

      searchFlag: 1, // 1:显示历史记录和热门搜索 2: 显示搜索中展示列表 3:搜索商品列表 4:空页面

      searchRecordHistory:
        JSON.parse(localStorage.getItem('search_history')) || [], // 历史记录

      currentCategoryIndex: 0, // 子组件分类的tag标签的默认index
      sonSpaceFlag: false, // 子组件空白页是否显示
    };
  },
  mounted() {
    this.getHotKeywordList();
  },
  methods: {
    // 获取热搜索词
    getHotKeywordList() {
      this.$store.dispatch('getHotKeywordList');
    },

    // 输出获取搜索关键词
    async getSearchKeyWord(val) {
      try {
        const result = await this.$store.dispatch('getSearchKeywordList', val);
        this.keywordList = result;
      } catch (error) {
        Toast.fail('获取关键词失败');
      }
    },

    // 点击tag去searchShopList
    async toSearchShopList(
      keyword,
      descSorted,
      _stat_search,
      categoryId,
      floorPrice,
      upperPrice
    ) {
      let obj = {
        keyword,
        descSorted,
        _stat_search,
        categoryId,
        floorPrice,
        upperPrice,
      };
      this.value = keyword; // 保存关键字
      this.currentCategoryIndex = 0; // 清除分类index

      await this.$store.dispatch('getSearchShopInfo', obj);

      // 将子组件data恢复原状
      this.$refs.searchShopList.comprehensiveSortFlag = true;
      this.$refs.searchShopList.floorPrice = '';
      this.$refs.searchShopList.upperPrice = '';

      this.sonSpaceFlag = false; // 开启子组件商品列表
      this.searchFlag = 3;
    },

    // 获取焦点时触发
    onFocus() {
      // 清空搜索关键词列表
      this.keywordList = [];
      // 获取搜索关键词列表
      this.getSearchKeyWord(this.value);
      // 展示搜索展示页面
      this.searchFlag = 2;
    },

    // enter或点击cell搜索时触发
    async onSearch(val, type) {
      // 点击时清除分类的index
      this.currentCategoryIndex = 0;
      this.searchFlag = -1; // 先什么页面都没有
      this.value = val;
      let arr = [];
      this.searchCellListFlag = false;

      // 创建历史记录
      if (!localStorage.getItem('search_history')) {
        arr.unshift(val);
        localStorage.setItem('search_history', JSON.stringify(arr));
      } else {
        arr = JSON.parse(localStorage.getItem('search_history'));
        let findIndex = arr.findIndex(item => item === val);
        // 如果没有重复，才加入历史记录
        if (findIndex !== -1) {
          arr.unshift(arr.splice(findIndex, 1)[0]);
        } else {
          if (arr.length >= 10) {
            arr.pop();
          }
          arr.unshift(val);
        }
        localStorage.setItem('search_history', JSON.stringify(arr));
      }
      this.searchRecordHistory = arr; // 保存历史记录

      // 搜索
      await this.toSearchShopList(val, false, type);
      if (this.machType === 0) {
        this.searchFlag = 4;
        return;
      }

      this.sonSpaceFlag = false; // 开启子组件商品列表

      // 展示搜索商品列表
      this.searchFlag = 3;
    },

    // 点击取消时触发
    onCancel() {
      if (this.searchFlag === 1) {
        this.$router.push('/home');
      } else {
        this.searchFlag = 1;
        Toast('取消');
      }
    },

    // 输入时触发
    onInput: debounce(
      function (val) {
        if (!val) {
          // 如果值为空，则都关闭
          this.searchFlag = 1;
        } else {
          // 防止再次输入
          this.searchFlag = 2;
          // 防抖：用户一段时间不输入再发请求
          this.getSearchKeyWord(val);
        }
      },
      400,
      { trailing: true }
    ),

    // 删除历史记录
    deleteHistory() {
      this.searchRecordHistory = [];
      localStorage.removeItem('search_history');
    },

    // 商品列表点击分类搜索
    async priceAndCategorySort(categoryId, floorPrice, upperPrice, descSorted) {
      let obj = {};
      // console.log(categoryId, floorPrice, upperPrice, descSorted);
      if (floorPrice) {
        obj.floorPrice = floorPrice;
      }
      if (floorPrice) {
        obj.upperPrice = upperPrice;
      }

      if (descSorted !== -1) {
        obj.descSorted = descSorted;
      }
      obj.keyword = this.value;
      obj.categoryId = categoryId;
      await this.$store.dispatch('getSearchShopInfo', obj);
      if (!this.hasMore && !this.searchShopList.length) {
        this.sonSpaceFlag = true; // 开启筛选空白页
      } else {
        this.sonSpaceFlag = false; // 否则则开启商品列表页
      }
    },

    // 价格排序
  },
  computed: {
    ...mapState({
      hotKeywordList: state => state.search.hotKeywordList,
      searchHistory: state => state.search.searchHistory,
    }),

    ...mapGetters(['machType', 'hasMore', 'searchShopList']),
  },
  components: {
    SearchShopList,
  },
};
</script>

<style lang="less" scoped>
.searchContainer {
  .search {
    position: fixed !important;
    left: 0;
    top: 0;
    z-index: 5;
    width: 100%;
    background-color: #fff;
  }
  // 热搜
  .record-hot {
    margin-top: 54px;
    // 历史记录
    .record-wrap {
      padding: 0 15px;
      .record {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 45px;
        font-size: 16px;
        color: #999999;
        .delete {
          font-size: 20px;
        }
      }
      .tag-list {
        margin-bottom: 10px;
        margin-top: -20px;
        .tag {
          margin-right: 16px;
          &:active {
            background-color: #cccccc;
            color: #fff;
          }
        }
      }
    }
    .gray {
      height: 10px;
      background-color: #eee;
    }

    // 热搜条
    .hot-search {
      background-color: #fff;
      padding: 0 15px;
      .hot-search-text {
        height: 45px;
        line-height: 45px;
        font-size: 14px;
        color: #999;
      }
      .tag-list {
        margin-top: -20px;
        padding: 0;
        .tag {
          margin-right: 16px;
          &.active {
            &:active {
              background-color: #dd1a21;
              color: #fff !important;
            }
          }
          &:active {
            background-color: #cccccc;
            color: #fff;
          }
        }
      }
    }
  }

  // 搜索时展示cell
  .search-inp {
    .search-tag {
      border-bottom: 1px solid #999;
    }
  }
}
</style>
